var express = require("express");
var router = express.Router();
var models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const jwtSecretKey = require("../utils/jwtSecretKey");

// 注册
router.post("/register", async function (req, res, next) {
  const where1 = {};
  const where2 = {};
  const username = req.body.username;
  const password = req.body.password;
  const email = req.body.email;
  const captcha = req.body.captcha;
  const emailCaptcha = req.body.emailCaptcha;
  if (!username || !password)
    return res.json({
      code: 400,
      msg: "账号或密码不能为空",
    });
  if (username) {
    where1.username = {
      [Op.like]: username,
    };
  }
  if (email) {
    where2.email = {
      [Op.like]: email,
    };
  }
  var data1 = await models.User.findAndCountAll({
    where: where1,
  });
  if (data1.count > 0)
    return res.json({
      code: 400,
      msg: "账号已存在，请使用新的用户名注册",
    });
  var data2 = await models.User.findAndCountAll({
    where: where2,
  });
  if (data2.count > 0)
    return res.json({
      code: 400,
      msg: "该邮箱已被注册，请使用新的邮箱注册",
    });
  if (!bcrypt.compareSync(captcha, emailCaptcha)) {
    return res.json({
      code: 400,
      msg: "验证码错误",
    });
  }
  await models.User.create({
    username: username,
    email: email,
    password: bcrypt.hashSync(password, 10),
    role: 0,
  });
  res.json({
    code: 200,
    msg: "注册成功",
  });
});

// 登录
router.post("/login", async function (req, res, next) {
  const where = {};
  const username = req.body.username;
  const password = req.body.password;
  if (!username || !password)
    return res.json({
      code: 400,
      msg: "账号或密码不能为空",
    });
  if (username) {
    where.username = {
      [Op.like]: username,
    };
  }
  var data = await models.User.findAndCountAll({
    where: where,
  });
  if (data.count == 0)
    return res.json({
      code: 400,
      msg: "用户不存在",
    });
  console.log(data);
  const compareResult = bcrypt.compareSync(password, data.rows[0].password);
  if (!compareResult)
    return res.status(400).json({
      code: 400,
      msg: "账号或密码错误",
    });

  const user = {
    id: data.rows[0].id,
    username: data.rows[0].username,
    password: data.rows[0].password,
  };
  const tokenStr = jwt.sign(user, jwtSecretKey.jwtSecretKey, {
    expiresIn: "10d",
    algorithm: "HS384",
  });
  res.json({
    code: 200,
    msg: "登录成功",
    token: "Bearer " + tokenStr,
  });
});

// 查询人员列表
router.get("/", async function (req, res, next) {
  const where = {};
  const currentPage = parseInt(req.query.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.query.pageSize) || 10; // 分页参数
  const major = req.query.major;
  const college = req.query.college;
  const gender = req.query.gender;
  const grade = req.query.grade;
  const name = req.query.name;
  const stuCode = req.query.stuCode;
  const society = req.query.society;
  if (major) {
    where.major = {
      [Op.like]: major,
    };
  }
  if (college) {
    where.college = {
      [Op.like]: college,
    };
  }
  if (grade) {
    where.grade = {
      [Op.like]: grade,
    };
  }
  if (gender) {
    where.gender = {
      [Op.like]: gender,
    };
  }
  if (name) {
    where.name = {
      [Op.like]: "%" + name + "%",
    };
  }
  if (stuCode) {
    where.stuCode = {
      [Op.like]: "%" + stuCode + "%",
    };
  }
  if (society) {
    where.society = {
      [Op.like]: '%'+  "-" + society + "-" + '%',
    };
  }
  var result = await models.User.findAndCountAll({
    order: [["id", "desc"]], // 根据某个字段进行排序， desc-降序 asc-升序
    where: where,
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 根据Id查询
router.get("/userId/:id", async function (req, res, next) {
  var data = await models.User.findByPk(req.params.id);
  res.json({
    code: 200,
    msg: "操作成功",
    data: data,
  });
});

// 获取当前用户信息
router.get("/userInfo", async function (req, res, next) {
  var data = await models.User.findByPk(req.auth.id);
  res.json({
    code: 200,
    msg: "操作成功",
    data: data,
  });
});

// 修改人员
router.put("/userInfo", async function (req, res, next) {
  // findByPk是通过主键查找
  const data = await models.User.findByPk(req.body.id);
  data.update(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 修改密码
router.put("/password", async function (req, res, next) {
  const where = {};
  const password = req.body.password;
  const email = req.body.email;
  const captcha = req.body.captcha;
  const emailCaptcha = req.body.emailCaptcha;
  if (!email || !password || !captcha)
    return res.json({
      code: 400,
      msg: "请完整地填写表单",
    });
  if (!bcrypt.compareSync(captcha, emailCaptcha)) {
    return res.json({
      code: 400,
      msg: "验证码错误",
    });
  }
  where.email = {
    [Op.like]: email,
  };
  var data = await models.User.findOne({
    where: where,
  });
  data.update({ password: bcrypt.hashSync(password, 10) });
  res.json({
    code: 200,
    msg: "修改成功",
  });
});

// 删除人员
router.delete("/:id", async function (req, res, next) {
  // findByPk是通过主键查找
  var data = await models.User.findByPk(req.params.id);
  data.destroy(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

module.exports = router;
